import os
import webbrowser

class SvgPreview:

    def __init__(self, target_dir) -> None:
        self.target_dir = target_dir
        vectors = []
        for path in os.listdir(self.target_dir):
            item = {}
            is_svg, content = self.xml2svg(self.target_dir + path)    
            if is_svg:
                item["name"] = path
                item["svg"] = content
                vectors.append(item)
        
        html_str = self.output_html(vectors)

        self.output("output_template.html", html_str)
        webbrowser.open("output_template.html")
        pass

    def xml2svg(self, path):
        content = ""
        try:
            # 读配置
            with open(path, 'r',encoding='UTF-8') as f:
                content = f.read()

            is_svg = "vector" in content
            content = content.replace("vector", "svg")
            content = content.replace("xmlns:android", "xmlns")
            content = content.replace("android:", "")
            content = content.replace("fillColor", "fill")
            content = content.replace("pathData", "d")
            content = content.replace("http://schemas.android.com/apk/res/android", "http://www.w3.org/2000/svg")    
            content = content.replace("gradient", "linearGradient")    
            content = content.replace("startX", "x1")    
            content = content.replace("startY", "y1")    
            content = content.replace("endX", "x2")    
            content = content.replace("endY", "y2")    
            content = content.replace("fillType", "fill-rule")    
            content = content.replace("item", "stop")    
        except:
            return False, ""    
        return is_svg, content
    
    def output_html(self, vectors):
        content = ""
         # 读配置
        with open("template.html", 'r',encoding='UTF-8') as f:
            content = f.read()
        
        start_idx = content.index("{for-start}")
        end_idx = content.index("{for-end}")


        for_content = content[start_idx:end_idx]
        for_content = for_content.replace("{for-start}","")

        for_content_full = ""
        for vector in vectors:
            new_content = for_content
            new_content = new_content.replace("{svg}", vector["svg"])
            new_content = new_content.replace("{svg-name}", vector["name"])
            for_content_full = for_content_full + new_content + "\r\n"

        content = content.replace(for_content, for_content_full)
        content = content.replace("{for-start}", "")
        content = content.replace("{for-end}", "")
        content = content.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "")
        return content

    def output(self, path, content):
        with open(path, 'w',encoding='UTF-8') as f:
            f.write(content)


SvgPreview(target_dir = "D:/android_workspace/majlistar_android/sdk_lib/sdk_widget/src/main/res/drawable/")